<template>
  <div class="reception-container">
    <!-- 顶部操作栏 -->
    <div class="operation-bar">
      <div class="left-actions">
        <el-button type="primary" @click="showCheckinDialog = true">
          <el-icon><UserFilled /></el-icon>
          办理入住
        </el-button>
        <el-button type="success" @click="showCheckoutDialog = true">
          <el-icon><SuitcaseLine /></el-icon>
          办理退房
        </el-button>
        <el-button type="warning" @click="showReservationDialog = true">
          <el-icon><Calendar /></el-icon>
          新增预订
        </el-button>
      </div>
      <div class="right-actions">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索客人姓名、房间号、手机号"
          style="width: 300px"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-cards">
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-icon" style="background: #409eff">
            <el-icon :size="24"><UserFilled /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.checkedIn }}</div>
            <div class="stat-label">在住客人</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-icon" style="background: #67c23a">
            <el-icon :size="24"><Calendar /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.todayReservations }}</div>
            <div class="stat-label">今日预订</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-icon" style="background: #e6a23c">
            <el-icon :size="24"><Clock /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.pendingCheckout }}</div>
            <div class="stat-label">待退房</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-icon" style="background: #f56c6c">
            <el-icon :size="24"><Warning /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.overdue }}</div>
            <div class="stat-label">逾期未退</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 主要内容区域 -->
    <el-row :gutter="20" class="main-content">
      <!-- 左侧：在住客人列表 -->
      <el-col :span="12">
        <el-card class="guest-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span class="card-title">在住客人</span>
              <el-tag type="info">{{ filteredGuests.length }} 人</el-tag>
            </div>
          </template>
          <div class="guest-list">
            <div
              v-for="guest in filteredGuests"
              :key="guest.id"
              class="guest-item"
              @click="selectGuest(guest)"
              :class="{ active: selectedGuest?.id === guest.id }"
            >
              <div class="guest-avatar">
                <el-avatar :size="40">{{ guest.guestName.charAt(0) }}</el-avatar>
              </div>
              <div class="guest-info">
                <div class="guest-name">{{ guest.guestName }}</div>
                <div class="guest-phone">{{ guest.guestPhone }}</div>
                <div class="room-info">{{ guest.roomNumber }} - {{ guest.roomType }}</div>
              </div>
              <div class="guest-status">
                <el-tag :type="getStatusType(guest.status)" size="small">
                  {{ getStatusText(guest.status) }}
                </el-tag>
                <div class="checkin-time">{{ formatDate(guest.checkinTime) }}</div>
              </div>
              <div class="guest-actions">
                <el-button type="text" size="small" @click.stop="viewGuestDetail(guest)">
                  详情
                </el-button>
                <el-button type="text" size="small" @click.stop="checkoutGuest(guest)">
                  退房
                </el-button>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧：今日预订列表 -->
      <el-col :span="12">
        <el-card class="reservation-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span class="card-title">今日预订</span>
              <el-tag type="success">{{ todayReservations.length }} 单</el-tag>
            </div>
          </template>
          <div class="reservation-list">
            <div
              v-for="reservation in todayReservations"
              :key="reservation.id"
              class="reservation-item"
            >
              <div class="reservation-info">
                <div class="guest-name">{{ reservation.guestName }}</div>
                <div class="guest-phone">{{ reservation.guestPhone }}</div>
                <div class="room-info">
                  {{ reservation.roomType }} × {{ reservation.roomCount }}
                </div>
                <div class="date-info">
                  {{ formatDate(reservation.checkinDate) }} - {{ formatDate(reservation.checkoutDate) }}
                </div>
              </div>
              <div class="reservation-status">
                <el-tag :type="getReservationStatusType(reservation.status)" size="small">
                  {{ getReservationStatusText(reservation.status) }}
                </el-tag>
                <div class="amount">¥{{ reservation.totalAmount }}</div>
              </div>
              <div class="reservation-actions">
                <el-button
                  v-if="reservation.status === 'confirmed'"
                  type="primary"
                  size="small"
                  @click="checkinReservation(reservation)"
                >
                  入住
                </el-button>
                <el-button type="text" size="small" @click="viewReservationDetail(reservation)">
                  详情
                </el-button>
                <el-button
                  v-if="reservation.status === 'confirmed'"
                  type="text"
                  size="small"
                  @click="cancelReservation(reservation)"
                >
                  取消
                </el-button>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 入住对话框 -->
    <CheckinDialog
      v-model="showCheckinDialog"
      :reservation="selectedReservation"
      @success="handleCheckinSuccess"
    />

    <!-- 退房对话框 -->
    <CheckoutDialog
      v-model="showCheckoutDialog"
      :guest="selectedGuest"
      @success="handleCheckoutSuccess"
    />

    <!-- 预订对话框 -->
    <ReservationDialog
      v-model="showReservationDialog"
      @success="handleReservationSuccess"
    />

    <!-- 客人详情对话框 -->
    <GuestDetailDialog
      v-model="showGuestDetailDialog"
      :guest="selectedGuest"
    />

    <!-- 预订详情对话框 -->
    <ReservationDetailDialog
      v-model="showReservationDetailDialog"
      :reservation="selectedReservation"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  UserFilled,
  SuitcaseLine,
  Calendar,
  Search,
  Refresh,
  Clock,
  Warning
} from '@element-plus/icons-vue'
import CheckinDialog from './components/CheckinDialog.vue'
import CheckoutDialog from './components/CheckoutDialog.vue'
import ReservationDialog from './components/ReservationDialog.vue'
import GuestDetailDialog from './components/GuestDetailDialog.vue'
import ReservationDetailDialog from './components/ReservationDetailDialog.vue'
import { getGuestList, getReservationList, getReceptionStats } from '@/api/reception'
import dayjs from 'dayjs'

// 响应式数据
const searchKeyword = ref('')
const showCheckinDialog = ref(false)
const showCheckoutDialog = ref(false)
const showReservationDialog = ref(false)
const showGuestDetailDialog = ref(false)
const showReservationDetailDialog = ref(false)
const selectedGuest = ref(null)
const selectedReservation = ref(null)

// 统计数据
const stats = reactive({
  checkedIn: 156,
  todayReservations: 23,
  pendingCheckout: 8,
  overdue: 2
})

// 在住客人列表
const guestList = ref([
  {
    id: 1,
    guestName: '张三',
    guestPhone: '13800138001',
    roomNumber: '301',
    roomType: '豪华套房',
    checkinTime: new Date(),
    checkoutTime: new Date(Date.now() + 2 * 24 * 60 * 60 * 1000),
    status: 'checked_in'
  },
  {
    id: 2,
    guestName: '李四',
    guestPhone: '13800138002',
    roomNumber: '205',
    roomType: '标准双人间',
    checkinTime: new Date(Date.now() - 24 * 60 * 60 * 1000),
    checkoutTime: new Date(Date.now() + 24 * 60 * 60 * 1000),
    status: 'checked_in'
  },
  {
    id: 3,
    guestName: '王五',
    guestPhone: '13800138003',
    roomNumber: '102',
    roomType: '商务套房',
    checkinTime: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000),
    checkoutTime: new Date(Date.now() - 60 * 60 * 1000),
    status: 'overdue'
  }
])

// 今日预订列表
const reservationList = ref([
  {
    id: 1,
    reservationNumber: 'R202412250001',
    guestName: '赵六',
    guestPhone: '13800138004',
    roomType: '豪华套房',
    roomCount: 1,
    checkinDate: new Date(),
    checkoutDate: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000),
    totalAmount: 1200,
    status: 'confirmed'
  },
  {
    id: 2,
    reservationNumber: 'R202412250002',
    guestName: '孙七',
    guestPhone: '13800138005',
    roomType: '标准双人间',
    roomCount: 2,
    checkinDate: new Date(),
    checkoutDate: new Date(Date.now() + 2 * 24 * 60 * 60 * 1000),
    totalAmount: 800,
    status: 'confirmed'
  }
])

// 计算属性
const filteredGuests = computed(() => {
  if (!searchKeyword.value) return guestList.value
  
  const keyword = searchKeyword.value.toLowerCase()
  return guestList.value.filter(guest => 
    guest.guestName.toLowerCase().includes(keyword) ||
    guest.guestPhone.includes(keyword) ||
    guest.roomNumber.includes(keyword)
  )
})

const todayReservations = computed(() => {
  return reservationList.value.filter(reservation => 
    dayjs(reservation.checkinDate).isSame(dayjs(), 'day')
  )
})

// 方法
const formatDate = (date) => {
  return dayjs(date).format('MM-DD HH:mm')
}

const getStatusType = (status) => {
  const statusMap = {
    checked_in: 'success',
    overdue: 'danger',
    pending_checkout: 'warning'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    checked_in: '在住',
    overdue: '逾期',
    pending_checkout: '待退房'
  }
  return statusMap[status] || '未知'
}

const getReservationStatusType = (status) => {
  const statusMap = {
    confirmed: 'success',
    pending: 'warning',
    cancelled: 'danger',
    checked_in: 'info'
  }
  return statusMap[status] || 'info'
}

const getReservationStatusText = (status) => {
  const statusMap = {
    confirmed: '已确认',
    pending: '待确认',
    cancelled: '已取消',
    checked_in: '已入住'
  }
  return statusMap[status] || '未知'
}

const selectGuest = (guest) => {
  selectedGuest.value = guest
}

const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

const refreshData = async () => {
  try {
    await loadData()
    ElMessage.success('数据已刷新')
  } catch (error) {
    ElMessage.error('刷新失败')
  }
}

const viewGuestDetail = (guest) => {
  selectedGuest.value = guest
  showGuestDetailDialog.value = true
}

const checkoutGuest = (guest) => {
  selectedGuest.value = guest
  showCheckoutDialog.value = true
}

const viewReservationDetail = (reservation) => {
  selectedReservation.value = reservation
  showReservationDetailDialog.value = true
}

const checkinReservation = (reservation) => {
  selectedReservation.value = reservation
  showCheckinDialog.value = true
}

const cancelReservation = async (reservation) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消预订 ${reservation.reservationNumber} 吗？`,
      '取消预订',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用取消预订API
    reservation.status = 'cancelled'
    ElMessage.success('预订已取消')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消预订失败')
    }
  }
}

const handleCheckinSuccess = () => {
  showCheckinDialog.value = false
  selectedReservation.value = null
  refreshData()
}

const handleCheckoutSuccess = () => {
  showCheckoutDialog.value = false
  selectedGuest.value = null
  refreshData()
}

const handleReservationSuccess = () => {
  showReservationDialog.value = false
  refreshData()
}

const loadData = async () => {
  try {
    // 加载统计数据
    // const statsData = await getReceptionStats()
    // Object.assign(stats, statsData)
    
    // 加载客人列表
    // const guests = await getGuestList()
    // guestList.value = guests
    
    // 加载预订列表
    // const reservations = await getReservationList()
    // reservationList.value = reservations
  } catch (error) {
    console.error('加载数据失败:', error)
  }
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.reception-container {
  padding: 20px;
  background-color: var(--el-bg-color-page);
  min-height: calc(100vh - 84px);
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  
  .left-actions {
    display: flex;
    gap: 12px;
  }
  
  .right-actions {
    display: flex;
    gap: 12px;
    align-items: center;
  }
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  }
  
  .stat-icon {
    width: 50px;
    height: 50px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    margin-right: 16px;
  }
  
  .stat-content {
    .stat-number {
      font-size: 24px;
      font-weight: 600;
      color: var(--el-text-color-primary);
      margin-bottom: 4px;
    }
    
    .stat-label {
      font-size: 14px;
      color: var(--el-text-color-regular);
    }
  }
}

.main-content {
  .el-card {
    height: 600px;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .card-title {
    font-size: 16px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }
}

.guest-list,
.reservation-list {
  height: 520px;
  overflow-y: auto;
}

.guest-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    background-color: var(--el-fill-color-light);
  }
  
  &.active {
    background-color: var(--el-color-primary-light-9);
    border-color: var(--el-color-primary);
  }
  
  &:last-child {
    border-bottom: none;
  }
  
  .guest-avatar {
    margin-right: 12px;
  }
  
  .guest-info {
    flex: 1;
    
    .guest-name {
      font-size: 16px;
      font-weight: 500;
      color: var(--el-text-color-primary);
      margin-bottom: 4px;
    }
    
    .guest-phone {
      font-size: 14px;
      color: var(--el-text-color-regular);
      margin-bottom: 4px;
    }
    
    .room-info {
      font-size: 12px;
      color: var(--el-text-color-placeholder);
    }
  }
  
  .guest-status {
    text-align: center;
    margin-right: 12px;
    
    .checkin-time {
      font-size: 12px;
      color: var(--el-text-color-placeholder);
      margin-top: 4px;
    }
  }
  
  .guest-actions {
    display: flex;
    flex-direction: column;
    gap: 4px;
  }
}

.reservation-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  
  &:last-child {
    border-bottom: none;
  }
  
  .reservation-info {
    flex: 1;
    
    .guest-name {
      font-size: 16px;
      font-weight: 500;
      color: var(--el-text-color-primary);
      margin-bottom: 4px;
    }
    
    .guest-phone {
      font-size: 14px;
      color: var(--el-text-color-regular);
      margin-bottom: 4px;
    }
    
    .room-info {
      font-size: 14px;
      color: var(--el-text-color-regular);
      margin-bottom: 4px;
    }
    
    .date-info {
      font-size: 12px;
      color: var(--el-text-color-placeholder);
    }
  }
  
  .reservation-status {
    text-align: center;
    margin-right: 12px;
    
    .amount {
      font-size: 16px;
      font-weight: 600;
      color: var(--el-color-primary);
      margin-top: 4px;
    }
  }
  
  .reservation-actions {
    display: flex;
    flex-direction: column;
    gap: 4px;
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .main-content {
    .el-col {
      margin-bottom: 20px;
    }
  }
}

@media (max-width: 768px) {
  .reception-container {
    padding: 10px;
  }
  
  .operation-bar {
    flex-direction: column;
    gap: 16px;
    
    .left-actions,
    .right-actions {
      width: 100%;
      justify-content: center;
    }
    
    .right-actions {
      flex-direction: column;
    }
  }
  
  .stats-cards {
    .el-col {
      margin-bottom: 12px;
    }
  }
  
  .main-content {
    .el-card {
      height: auto;
      margin-bottom: 20px;
    }
  }
  
  .guest-list,
  .reservation-list {
    height: 400px;
  }
}
</style>